package com.xyz.code.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.dbcp.BasicDataSource;

public final class JdbcUtils {

	private static BasicDataSource ds = null;

	private static ConcurrentMap<String, Connection> clientConnectionMap = new ConcurrentHashMap<String, Connection>();

	private JdbcUtils() {

	}

	private static JdbcUtils instance = null;

	public static JdbcUtils getInstance() {
		if (instance == null) {
			synchronized (JdbcUtils.class) {
				if (instance == null) {
					instance = new JdbcUtils();
				}

			}
		}

		return instance;
	}

	// 注册驱动
	static {
		// ds = new BasicDataSource();
		// ds.setDriverClassName("com.mysql.jdbc.Driver");
		// ds.setUrl("jdbc:mysql://localhost:3306/test");
		// ds.setUsername("root");
		// ds.setPassword("root123");
		// ds.setMaxIdle(20);
		// ds.setInitialSize(4);
		ds = new BasicDataSource();
		ds.setDriverClassName(PropertiesUtil.getConfigValueCache(
				Constants.CONFIG_FILE, Constants.DRIVER_CLASS_NAME));
		ds.setUrl(PropertiesUtil.getConfigValueCache(Constants.CONFIG_FILE,
				Constants.DB_URL));
		ds.setUsername(PropertiesUtil.getConfigValueCache(Constants.CONFIG_FILE,
				Constants.DB_USER_NAME));
		ds.setPassword(PropertiesUtil.getConfigValueCache(Constants.CONFIG_FILE,
				Constants.DB_PASS_WORD));
		ds.setMaxIdle(new Integer(PropertiesUtil.getConfigValueCache(
				Constants.CONFIG_FILE, Constants.DB_MAX_IDLE)));
		ds.setInitialSize(new Integer(PropertiesUtil.getConfigValueCache(
				Constants.CONFIG_FILE, Constants.DB_INITIAL_SIZE)));
	}

	// 该方法获得连接
	public synchronized Connection getServerConnection() throws SQLException {
		return ds.getConnection();
	}

	public static BasicDataSource getDs() {
		return ds;
	}

	// 释放资源
	public static void free(Connection conn, Statement st, ResultSet rs) {

		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			try {
				if (st != null) {

					st.close();
				}
			} catch (SQLException e) {

				e.printStackTrace();
			} finally {
				try {
					if (conn != null) {

						conn.close();
					}
				} catch (SQLException e) {

					e.printStackTrace();
				}
			}
		}
	}

	public static void commitAndClose(Connection conn) {
		try {
			conn.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		} finally {
			try {
				if (conn != null) {
					conn.setAutoCommit(true);
					conn.close();
				}
			} catch (Exception e3) {
				e3.printStackTrace();
			}
		}
	}

}
